<?php
// 引入数据库类和工具函数
require_once __DIR__ . '/../func/db.class.php';
require_once __DIR__ . '/../func/utils.php';

// 创建数据库对象
$db = new Db();

// 获取POST请求数据
$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');

// 获取用户IP地址
$userIp = $_SERVER['REMOTE_ADDR'];

// 验证输入
if (empty($username) || empty($password)) {
    echo json_encode(['success' => false, 'message' => '用户名或密码不能为空']);
    exit;
}

if (strlen($password) < 6) {
    echo json_encode(['success' => false, 'message' => '密码长度不足6位']);
    exit;
}

// 检查用户名是否已存在
if ($db->userExists($username)) {
    echo json_encode(['success' => false, 'message' => '用户名已存在']);
    exit;
}

// 初始化session中的请求日志
if (!isset($_SESSION['request_log'])) {
    $_SESSION['request_log'] = [];
}

// 删除一小时前的记录
$currentTime = time();
$oneHourAgo = $currentTime - 3600;
$_SESSION['request_log'] = array_filter($_SESSION['request_log'], function($log) use ($oneHourAgo) {
    return $log['timestamp'] > $oneHourAgo;
});

// 获取过去三分钟内的请求次数
$threeMinutesAgo = $currentTime - 180;
$requestCount = 0;
foreach ($_SESSION['request_log'] as $log) {
    if ($log['ip'] == $userIp && $log['timestamp'] > $threeMinutesAgo) {
        $requestCount++;
    }
}

// 检查是否封禁
if (isset($_SESSION['banned_ips'][$userIp]) && $_SESSION['banned_ips'][$userIp] > $currentTime) {
    echo json_encode(['success' => false, 'message' => '您的IP地址已被封禁，请稍后再试']);
    exit;
}

// 如果请求次数超过10次，封禁IP地址
if ($requestCount >= 10) {
    $_SESSION['banned_ips'][$userIp] = $currentTime + 3600; // 封禁1小时
    echo json_encode(['success' => false, 'message' => '请求过于频繁，您的IP地址已被封禁1小时']);
    exit;
}

// 记录本次请求
$_SESSION['request_log'][] = [
    'ip' => $userIp,
    'timestamp' => $currentTime
];

// 插入新用户
try {
    $db->beginTransaction();

    // 对密码进行哈希处理
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // 插入用户数据
    $userId = $db->insert('users', [
        'username' => $username,
        'password' => $hashedPassword,
        'last_login_ip' => $userIp,
        'registration_ip' => $userIp
    ]);

    // 插入登录历史记录
    $db->insert('login_history', [
        'user_id' => $userId,
        'ip_address' => $userIp
    ]);

    // 提交事务
    $db->commit();

    echo json_encode(['success' => true, 'message' => '注册成功', 'username' => $username]);
} catch (Exception $e) {
    // 回滚事务
    $db->rollBack();

    echo json_encode(['success' => false, 'message' => '注册失败: ' . $e->getMessage()]);
}